package jwt

import (
	"easyblog/utils/errmsg"
	"github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go/v4"
	"time"
)

var jetSecret,_ = web.AppConfig.String("jwtsecret")
var JwtSecret = []byte(jetSecret)

type MyClaims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

/**
* GenerateToken
* @Description: 生成token
* @param username
* @return string
* @return int
*/
func GenerateToken(username string)(string ,int ){
	claims := MyClaims{
		Username: username,
		StandardClaims : jwt.StandardClaims{
			ExpiresAt: jwt.At(time.Now().Add(10*time.Hour)),
			Issuer: "easyblog",	//发行者
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedToken, err := token.SignedString(JwtSecret)
	if err != nil {
		return "",errmsg.ERROR
	}
	return signedToken,errmsg.SUCCSE
}

/**
* ParseToken
* @Description: 解析token
* @param tokenStr
* @return *MyClaims
* @return int
*/
func ParseToken(tokenStr string) (*MyClaims,int) {
	setToken,_ := jwt.ParseWithClaims(tokenStr,&MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return JwtSecret,nil
	})

	if claims,_ := setToken.Claims.(*MyClaims); setToken.Valid {
		return claims,errmsg.SUCCSE
	}else {
		return nil,errmsg.ERROR
	}
}